package org.csu.mypetstore_seller.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.mypetstore_seller.domain.Account;
import org.csu.mypetstore_seller.domain.AccountSign;
import org.csu.mypetstore_seller.persistence.AccountMapper;
import org.csu.mypetstore_seller.persistence.AccountSignMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountSignMapper accountSignMapper;

    //拿到所有账户信息
    public List<Account> getAllAccount(){
        return accountMapper.selectList(null);
    }

    //拿到单个账户信息
    public Map<String,Object> getOneAccount(String username){
        Map<String,Object> map = new HashMap<>();
        map.put("account", accountMapper.selectById(username));//从账户表
        map.put("accountSign", accountSignMapper.selectById(username));//从登录表
        return map;
    }

    public String updateAccount(Account account){
        try{
            accountMapper.updateById(account);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return "出错啦！";
        }
        return "用户信息修改成功！";
    }

    public String updatePassword(String userId, String newPassword) {
        try {
            AccountSign accountSign = accountSignMapper.selectById(userId);
            if (accountSign == null) {
                return "用户不存在";
            }
            accountSign.setPassword(newPassword); // 更新密码
            accountSignMapper.updateById(accountSign);
            return "密码更新成功！";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "出错啦！";
        }
    }

    public String resetPassword(String userid){
        try{
            AccountSign accountSign = accountSignMapper.selectById(userid);
            accountSign.setPassword("123456");
            accountSignMapper.updateById(accountSign);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return "出错啦！";
        }
        return "重置密码成功！";
    }

    //同时修改账户表和登录表
    public String updateUsername(String newUserid, Account account){
        try{
            if(accountMapper.selectById(newUserid) != null){
                return "用户名已存在，换个名字吧！";
            }else{
                String oldId = account.getUserid();//获取原用户名

                //删除旧的数据，插入新数据
                accountMapper.deleteById(account);
                account.setUserid(newUserid);//同步修改
                accountMapper.insert(account);
                AccountSign accountSign = accountSignMapper.selectById(oldId);
                accountSignMapper.deleteById(oldId);
                accountSign.setUsername(newUserid);
                accountSignMapper.insert(accountSign);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            return "出错啦！";
        }
        return "更改用户名成功！";
    }

    public String deleteAccount(String userid){
        try{
            accountMapper.deleteById(userid);
            accountSignMapper.deleteById(userid);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return "出错啦！";
        }
        return "删除用户成功！";
    }

    public String addAccount(Account account, AccountSign accountSign){
        // 检查用户名是否为空
        if(account.getUserid() == null || account.getUserid().trim().isEmpty()){
            return "用户名不能为空！"; // 返回错误信息，类似于用户名重复的情况
        }
        try{
            // 设置新用户的默认状态为 "OK"
            account.setStatus("OK");
            accountMapper.insert(account);
            if (accountSign.getPassword() == null || accountSign.getPassword().trim().isEmpty()) {
                accountSign.setPassword("123456");
            }
            else
                accountSign.setPassword(accountSign.getPassword());
            accountSignMapper.insert(accountSign);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return "用户名已存在，换个名字吧！";
        }
        return "添加用户成功！";
    }

    //MD5加密(将数据转换为MD5哈希值)
    public String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16){
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }
    public Integer getNum(){
        return accountMapper.selectList(null).size();
    }//获取用户总数

    //获取状态正常用户(OK)
    public Integer getNum1(){
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "OK");
        return accountMapper.selectList(queryWrapper).size();
    }
}
